<template>
  <ContentCard
    ><template #header>
      <pageHeaderNew title="储存管理" :breadCrumb="breadCrumb"></pageHeaderNew>
    </template>
    <div class="content">
      <div>
        <a-space direction="vertical" fill :size="30">
          <div>
            <a-space>
              <div>盘容量分配方式</div>
              <a-radio-group v-model="allocationType">
                <a-radio :value="1">统一分配</a-radio>
                <a-radio :value="2">自由分配</a-radio>
              </a-radio-group>
            </a-space>
          </div>
          <div v-if="allocationType === 1">
            <a-space>
              <a-space
                ><span>每人各</span
                ><a-input-number
                  :style="{ width: '100px' }"
                  :min="0"
                  v-model="setAvgAmount"
                  :max="avgAmount"
                />GB</a-space
              >
              <div>当前盘符总容量:{{ diskSpace }}GB</div>
              <div>共:{{ humanAmount }}人</div>
              <a-button
                style="margin-left: 50px"
                type="primary"
                @click="editStorageSpace"
                >确认平均分配</a-button
              >
            </a-space>
          </div>
          <div v-if="allocationType === 2">
            <a-space :size="50">
              <a-select
                :style="{ width: '320px' }"
                placeholder="选择成员"
                v-model="selectUser"
              >
                <a-option
                  v-for="item in userData"
                  :key="item.id"
                  :value="item.id"
                  >{{ item.name }}</a-option
                >
              </a-select>
              <div>
                个人容量上限
                <a-input-number
                  :style="{ width: '100px' }"
                  :min="0"
                  :max="avgAmount"
                  v-model="userDiskAmount"
                />
                GB
              </div>
              <a-button type="primary" @click="setUserDisk"
                >保存</a-button
              ></a-space
            >
          </div>
        </a-space>
      </div>

      <div class="table-box" style="margin-top: 20px">
        <TableTurn :tableData="getTableData" ref="tableRef" :args="args">
          <a-table-column :width="80">
            <template #title> 序号 </template>
            <template #cell="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
          </a-table-column>

          <a-table-column :width="200" data-index="name" title="成员">
          </a-table-column>
          <a-table-column :width="200" data-index="" title="已用空间">
            <template #cell="{ record }">{{
              bytesToSize(record.usedDiskSpace) || '暂无'
            }}</template>
          </a-table-column>
          <a-table-column :width="200" data-index="" title="空间上限">
            <template #cell="{ record }"
              >{{ bytesToSize(record.diskSpace) || '暂无' }}
            </template>
          </a-table-column>
        </TableTurn>
      </div>
    </div>

    <FilePreview
      v-model:visible="PreviewModelVisible"
      ref="previewFileRef"
      v-if="previewFile.fileShow"
      :file="previewFile.fileMessage"
      @downLoadFile="downLoadFile"
    >
    </FilePreview
  ></ContentCard>
</template>

<script lang="ts" setup>
import {
  getUserDisk,
  getHumanStorageSpace,
  postUserDisk,
  putUserDisk,
  getUserList
} from '@/apis/document/documentCenter/index';

const tableRef = ref();
const allocationType = ref(1);
const StorageSpace = ref();
const avgAmount = ref();
const diskSpace = ref();
const userDiskAmount = ref();
const humanAmount = ref();
const setAvgAmount = ref();
const userData = ref();
const selectUser = ref();
const getUserData = async () => {
  const res = await getUserList({ pageNumber: 0, pageSize: -1 });
  console.log(res);
  userData.value = res.content;
};
getUserData();

const bToGb = (b: number): number => {
  return b / (1024 * 1024 * 1024);
};
const getTableData = async (page: any) => {
  try {
    const res = await getUserDisk({ ...page });
    const msg = await getUserList({ ...page });
    msg.content.forEach((item) => {
      const index = res.content.findIndex((ele) => ele.userId === item.id);
      if (index > -1) {
        item.diskSpace = res.content[index].diskSpace;
        item.usedDiskSpace = res.content[index].usedDiskSpace;
        item.diskId = res.content[index].id;
      }
    });
    userData.value = msg.content;
    console.log(msg);
    return Promise.resolve(msg);
  } catch (err: unknown) {
    console.log(err);
  }
};

const getHumanSpaceInto = async () => {
  const res = await getHumanStorageSpace();
  avgAmount.value = Number(bToGb(res.avgAmount).toFixed(2));
  diskSpace.value = Number(bToGb(res.diskSpace).toFixed(2));
  console.log(res, avgAmount.value, diskSpace.value);
};
getHumanSpaceInto();

const previewFile = reactive({
  fileShow: false,
  fileMessage: {
    id: '',
    fileName: '',
    downloadUrl: ''
  }
});
const PreviewModelVisible = ref(false);

const setPreview = (val: any) => {
  previewFile.fileMessage.id = val.id;
  previewFile.fileMessage.fileName = val.fileName;
  previewFile.fileMessage.downloadUrl = val.downloadPath;
  previewFile.fileShow = true;
  PreviewModelVisible.value = true;
};

const editStorageSpace = async () => {
  setAvgAmount.value = Math.trunc(setAvgAmount.value * 1024 * 1024 * 1024);
  console.log(setAvgAmount.value);
  await postUserDisk({ type: setAvgAmount.value });
  getHumanSpaceInto();
  tableRef.value.loadData();
};

const setUserDisk = async () => {
  if (!selectUser.value && !userDiskAmount.value) return;
  const index = userData.value.findIndex((ele) => ele.id === selectUser.value);
  let msg: any = {};
  if (userData.value[index].diskId) msg.id = userData.value[index].diskId;
  msg.userId = selectUser.value;
  msg.diskSpace = Math.trunc(userDiskAmount.value * 1024 * 1024 * 1024);
  await putUserDisk({ ...msg });
  tableRef.value.loadData();
};

function bytesToSize(bytes) {
  if (!bytes) return '0 B';
  var k = 1024, // or 1024
    sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
    i = Math.floor(Math.log(bytes) / Math.log(k));
  return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}
</script>

<style scoped lang="less">
.content {
  padding: 10px;
  height: 100%;
  width: 100%;
}

.search-box {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  width: 96%;
  margin: 10px;
}

:deep(.arco-table-tr) {
  height: 40px;
}
:deep(.arco-table-th) {
  font-weight: bold;
  // font-size: 13px;
}
</style>
